﻿using Consul;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Dev.MicroService.Framework.ConsulExtend.DispatcherExtend;
using Dev.MicroService.Framework.HttpApiExtend;
using Dev.MicroService.Interface;
using Dev.MicroService.Model;

namespace Dev.MicroService.Client.Controllers
{
    /// <summary>
    /// dotnet run --urls=http://*:5177
    /// </summary>
    public class APITestController : Controller
    {
        #region Identity
        private readonly ILogger<APITestController> _logger;
        private readonly IHttpAPIInvoker _iHttpAPIInvoker;
        private readonly AbstractConsulDispatcher _abstractConsulDispatcher;
        public APITestController(ILogger<APITestController> logger
            , IHttpAPIInvoker httpAPIInvoker
            , AbstractConsulDispatcher abstractConsulDispatcher)
        {
            this._logger = logger;
            this._iHttpAPIInvoker = httpAPIInvoker;
            this._abstractConsulDispatcher = abstractConsulDispatcher;
        }
        #endregion

        /// <summary>
        /// http://localhost:5177/APITest/Index
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            Console.WriteLine($"This is {nameof(APITestController)}.{nameof(Index)}");

            string url = "http://DevUserService/api/users/all";
            string realUrl = this._abstractConsulDispatcher.MapAddress(url);
            string content = this._iHttpAPIInvoker.InvokeApi(realUrl);
            base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            Console.WriteLine($"This is {realUrl} Invoke");
            return View();
        }
    }
}
